package com.qjkji.orderproject.core.service.impl;

import com.google.common.base.Preconditions;
import com.qjkji.orderproject.core.entity.User;
import com.qjkji.orderproject.core.exception.UnmessageException;
import com.qjkji.orderproject.core.mapper.UserMapper;
import com.qjkji.orderproject.core.service.UserService;
import com.qjkji.orderproject.core.util.SecurityUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    PasswordEncoder encoder;

    @Override
    public boolean registeredUser(User user) {
        if(userMapper.selectUserByName(user.getUsername()) != null){
            throw new UnmessageException("用户名已存在!");
        }
        user.setPassword(encoder.encode(user.getPassword()));
        return userMapper.insert(user) == 1;
    }


    @Override
    public boolean updatePassword(String oldPassword, String newPassword) {
        User user = userMapper.selectUserByName(SecurityUtil.getUserName());
        Preconditions.checkNotNull(user, "用户不存在!");
        if(encoder.matches(oldPassword, user.getPassword())){
            user.setPassword(encoder.encode(newPassword));
            return userMapper.updateById(user) == 1;
        }
        throw new UnmessageException("旧密码不对!");
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByName(String userName) {
        return userMapper.selectUserByName(userName);
    }
}
